use crate::states::AppState;
use actix_web::{web,HttpResponse};
use crate::models::Product;
//use chrono::Utc;
use crate::db_access::*;
//健康检查
pub async fn health_check_handler(
    app_state: web::Data<AppState>
) -> HttpResponse {
    let health_check_response = &app_state.health_check_response;
    let mut visit_count = app_state.visit_count.lock().unwrap();
    let response = 
        format!("{} {} times",health_check_response,visit_count);
    *visit_count += 1;
    HttpResponse::Ok().json(&response)
}

//产品信息
pub async fn products(
    app_state: web::Data<AppState>,
) -> HttpResponse {  
    let products = get_all_products(&app_state.db).await;
    HttpResponse::Ok().json("Success".to_string())       
}


//添加新产品
pub async fn new_product(
    new_product: web::Json<Product>,
    app_state: web::Data<AppState>,
) -> HttpResponse {
    HttpResponse::Ok().json("Success".to_string())
}

pub async fn get_all_product_with_id(
    app_state : web::Data<AppState>,
    //params : web::Path<i32>,
) -> HttpResponse {
        HttpResponse::Ok().json("Success".to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use actix_web::http::StatusCode;
    use std::sync::Mutex;
    use mysql::*;
    //测试添加新产品
    #[actix_rt::test]
    async fn post_new_product_test() {
        let url = "mysql://root:1234@localhost:3306/productDB";
    let opts = Opts::from_url(url).unwrap();
    let pool = Pool::new(opts).unwrap();//获取连接池
   // let db = pool.get_conn().unwrap();
        let app_state: web::Data<AppState> = web::Data::new(AppState {
             health_check_response: "welcome ".to_string(),
              visit_count: Mutex::new(0),
               db: pool
        });
        let product = web::Json(Product{
            id: 1001,
            product_no: 1002,
            product_type: "T恤".to_string(),
            product_suit_season: "春".to_string(),
            product_amount: 100, 
            product_name: "男T".to_string(),
            product_color: "黑色".to_string(),
            product_size: "L".to_string(),
            product_price: 99.9,
            product_note: "尺码偏大".to_string(),
            reserve1: " ".to_string(),
            reserve2: " ".to_string(),

        });


         let res = new_product(product,app_state).await;
         assert_eq!(res.status(),StatusCode::OK);
    }
    #[actix_rt::test]
    async fn get_product_with_id() {
        let url = "mysql://root:1234@localhost:3306/productDB";
    let opts = Opts::from_url(url).unwrap();
    let pool = Pool::new(opts).unwrap();//获取连接池
    //let db = pool.get_conn().unwrap();
        let app_state: web::Data<AppState> = web::Data::new(AppState {
             health_check_response: "welcome ".to_string(),
              visit_count: Mutex::new(0),
               db: pool
        });
        

        //let params : web::Path<i32> = web::Path::from(1);
        let res = get_all_product_with_id(app_state).await;
        assert_eq!(res.status(),StatusCode::OK);
    }
}
